﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Project32CHE.Biz.Goods.Extend.Providers
{
    /// <summary>
    /// 单据适配器工厂类
    /// </summary>
    public static class ProviderFactory
    {
        private static Dictionary<string, Type> dictProviderTypes = null;
        private static void load()
        {
            Assembly assembly = Assembly.GetCallingAssembly();
            Type[] childTypes = assembly.GetTypes();
            Type baseType = typeof(AbstractProvider);
            var list = new List<AbstractProvider>();
            foreach (Type type in childTypes)
            {
                if (!type.IsAbstract && type.IsSubclassOf(baseType))
                {
                    var item = (AbstractProvider)Activator.CreateInstance(type);
                    list.Add(item);
                }
            }
            if (dictProviderTypes != null) { dictProviderTypes.Clear(); }
            dictProviderTypes = list
                .GroupBy(x => x.Type, StringComparer.OrdinalIgnoreCase)
                .ToDictionary(k => k.Key, v => v.First().GetType(), StringComparer.OrdinalIgnoreCase);
        }
        static ProviderFactory()
        {
            load();
        }
        /// <summary>
        /// 注册指定单子类型的适配器
        /// </summary>
        /// <param name="type"></param>
        /// <param name="typeName"></param>
        public static void Register(Type type, string typeName = null)
        {
            Type baseType = typeof(AbstractProvider);
            if (type.IsAbstract || !type.IsSubclassOf(baseType))
            {
                throw new NotSupportedException("不支持的类型！");
            }
            if (string.IsNullOrWhiteSpace(typeName))
            {
                var item = (AbstractProvider)Activator.CreateInstance(type);
                typeName = item.Type;
            }
            dictProviderTypes[typeName] = type;
        }
        /// <summary>
        /// 获取指定单子类型的适配器
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static AbstractProvider Get(string type, Guid id)
        {
            Type providerType = null;
            if (!dictProviderTypes.TryGetValue(type, out providerType)) { throw new NotSupportedException("没有对应的单据适配程序！"); }
            var providerObject = (AbstractProvider)Activator.CreateInstance(providerType);
            providerObject.ChangeId(id);
            return providerObject;
        }
    }
}
